package com.dscyy.readutil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class InsertDbData {

	public static void main(String[] args) throws Exception {
		List<String> lineList = readFiles( "201809Vistors.sql");
		List<String> commitsql = new ArrayList<String>();
		int count=0;
		int allcount = 0;
		System.out.println("共有数据 " + lineList.size() +" 条。");
		for(String s : lineList){
			commitsql.add(s);
			count++;
			allcount++;
			if(count>1000) {
				commitSqlToDB(commitsql);
				commitsql = new ArrayList<String>();
				count=0;
				System.out.println("共有数据 " + lineList.size() +" 条,已提交 "+allcount );
			}
		}
		commitSqlToDB(commitsql);
		System.out.println("共有数据 " + lineList.size() +" 条,已提交 "+allcount );

	}
	
	public static void commitSqlToDB(List<String> sqls) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		//Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dscyy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "dscyy", "KeJ5AdNjmfrpMtba");
		Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dscyy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "dscyy", "KeJ5AdNjmfrpMtba");
		Statement stmt = conn.createStatement();
		for(String sql : sqls) {
			stmt.addBatch(sql);
		}
		stmt.executeBatch();
		stmt.close();
		conn.close();
	}
	
	public static List<String> readFiles(String filename) throws Exception {
		List<String> lineList = new ArrayList<String>();
		InputStreamReader isr = new InputStreamReader(new FileInputStream(filename), "utf-8"); // 或GB2312,GB18030
		BufferedReader read = new BufferedReader(isr); 
		String contentLine = read.readLine();
		while (contentLine != null) {
			lineList.add(contentLine);
			contentLine = read.readLine();
		}
		read.close();
		isr.close();
		return lineList;
	}

}
